package cn.emernet.demo2.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by hejx on 2018/8/28.
 */
public class HttpRequest {

    private HttpRequest() {
    }

    private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);
    private static final String UTF8 = "utf-8";
    /**
     * 超时时间
     */
    private static final int CONNECT_TIMEOUT = 10000;
    private static final int READ_TIMEOUT = 3000;

    /**
     * 取得 request 的真实IP
     *
     * @param request
     * @return
     */
    public final static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public final static String sendGet(String url, String param, Kv httpHeader) {
        String result = "";
        BufferedReader in = null;
        String urlNameString = url;
        if (param != null) {
            urlNameString += "?" + param;
        }
        try {
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(CONNECT_TIMEOUT);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Charset", UTF8);
            connection.setRequestProperty("contentType", UTF8);
            if (httpHeader != null && httpHeader.size() > 0) {
                httpHeader.forEach((k, v) -> {
                    connection.setRequestProperty((String) k, (String) v);
                });
            }
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            logger.warn("发送 GET 请求出现异常,请检查URL的正确性,目标服务器的运行状况! url=" + url + " " + e);
            logger.warn("param : " + param);
            e.printStackTrace();
            return null;
        } finally { // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("call url: " + url + " param: " + param + " get result: " + result);
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public final static String sendGet(String url) {
        return sendGet(url, null, null);
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public final static String sendPost(String url) {
        return sendPost(url, null);
    }

    public final static String sendPost(String url, String param) {
        return sendPost(url, param, null, null, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public final static String sendPost(String url, String param
            , Integer connTimeout, Integer readTimeout, Kv httpHeader) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", UTF8);
            conn.setRequestProperty("contentType", UTF8);
            if (httpHeader != null && httpHeader.size() > 0) {
                httpHeader.forEach((k, v) -> {
                    conn.setRequestProperty((String) k, (String) v);
                });
            }
            if (connTimeout == null) {
                conn.setConnectTimeout(CONNECT_TIMEOUT);
            } else {
                conn.setConnectTimeout(connTimeout);
            }
            if (readTimeout == null) {
                conn.setReadTimeout(READ_TIMEOUT);
            } else {
                conn.setReadTimeout(readTimeout);
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            if (param != null) {
                // 发送请求参数
                out.print(param);
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (SocketTimeoutException e) {

        } catch (IOException e) {
            logger.warn("发送 POST 请求出现异常,请检查URL的正确性,目标服务器的运行状况! url=" + url + " " + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
                if (in != null) in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("call url: " + url + " param: " + param + " get result: " + result);
        }
        return result;
    }

}
